﻿using System;
using System.Globalization;
using JetBrains.Annotations;

namespace SG.Ling.AutoTranslator.NLP
{
    public class CultureInfoDisplay : IEquatable<CultureInfoDisplay>, IEquatable<CultureInfo>
    {
        [NotNull]
        private readonly  CultureInfo _culture;

        public CultureInfoDisplay(CultureInfo culture)
        {
            if (culture == null)
                throw new ArgumentNullException("culture");

            _culture = culture;
        }

        public CultureInfo Culture
        {
            get { return _culture; }
        }

        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(obj, null))
                return false;

            if (obj is CultureInfo)
                return Equals((CultureInfo) obj);
            if (obj is CultureInfoDisplay)
                return Equals((CultureInfoDisplay) obj);

            return false;
        }

        public bool Equals(CultureInfoDisplay other)
        {
            return (object)other != null && other.Culture != null && other.Culture.LCID == Culture.LCID;
        }

        public bool Equals(CultureInfo other)
        {
            return other != null && other.LCID == Culture.LCID;
        }

        public static string ReplaceRegionPart(string name)
        {
            var paren = name.IndexOf('(');

            return (paren < 0 ? name : name.Substring(0, paren)).Trim();
        }

        public override string ToString()
        {
            if (Culture == CultureInfo.InvariantCulture)
                return "Automatic";

            var english = ReplaceRegionPart(Culture.EnglishName);
            var native = ReplaceRegionPart(Culture.NativeName);
            return string.Format("{0} ({1}{2})", english, Culture, english != native ? ", " + native : string.Empty);
        }

        public static implicit operator CultureInfo(CultureInfoDisplay @this)
        {
            return @this.Culture;
        }

        public static implicit operator CultureInfoDisplay(CultureInfo @this)
        {
            return new CultureInfoDisplay(@this);
        }

        public static bool operator ==(CultureInfoDisplay a, CultureInfoDisplay b)
        {
            return ReferenceEquals(a, b) || (object) a != null && a.Equals(b);
        }

        public static bool operator !=(CultureInfoDisplay a, CultureInfoDisplay b)
        {
            return !(a == b);
        }

        public override int GetHashCode()
        {
            return _culture.LCID;
        }
    }
}
